//
//  ComposeViewController.swift
//  WB
//
//  Created by leador on 17/5/12.
//  Copyright © 2017年 袁满. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    lazy var titleView:ComposeTitleView = ComposeTitleView()
    lazy var images: [UIImage] = [UIImage]()
    lazy var emoticonVc:EmoticonViewController = EmoticonViewController { (emoticon) in
        self.textView.insertEmoticon(emoticon: emoticon)
        self.textViewDidChange(self.textView)
    }
    
    @IBOutlet weak var textView: ComposeTextView!
    @IBOutlet weak var picPicker: picPickerCollectionView!

    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    @IBOutlet weak var picPickerHCons: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNavigationBar()
        
        setupNotification()

    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}

//MARK: ---设置UI界面---
extension ComposeViewController {
    
    func setupNavigationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closeClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(composeClick))
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        titleView.frame = CGRect(x: 0, y: 0, width: 200, height: 33)
        navigationItem.titleView = titleView
        
    }
    
    func setupNotification() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name:Notification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(addPhotoClick), name:Notification.Name(rawValue: addPhotoNotification) , object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(deletePhotoClick), name:Notification.Name(rawValue: deletePhotoNotification), object:nil)
        
    }
    
}

//MARK: ---事件监听---
extension ComposeViewController {
    
    func closeClick() {
        
        dismiss(animated: true, completion: nil)
        
    }
    
    func composeClick() {
        
        textView.resignFirstResponder()
        
        let status = textView.getEmoticonString()
        
        let image = images.first
        
        let finishCallBack = { (isSuccess:Bool) in
            
            if !isSuccess {
                SVProgressHUD.showError(withStatus: "发送微博失败")
                return
            }
            
            SVProgressHUD.showSuccess(withStatus: "发送微博成功")
            self.dismiss(animated: true, completion: nil)
            
        }
        
        if image != nil {
            
            NetworkTools.shareInstance.sendStatus(statusText: status, image: image!, isSuccess:finishCallBack)
            
        }else {
            
            NetworkTools.shareInstance.sendStatus(statusText: status, isSuccess: finishCallBack)
            
        }
        
    }
    
    func keyboardWillChangeFrame(note:NSNotification) {
        
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        
        let endFrame = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        
        UIView.animate(withDuration: duration) { 
            
            self.toolBarBottomCons.constant = kScreenHeight - endFrame.origin.y
            
        }
        
    }
    
    @IBAction func pickerVIewClick(_ sender: Any) {
        
        textView.resignFirstResponder()
        
        picPickerHCons.constant = kScreenHeight * 0.65
        
    }
    
    @IBAction func emojiBtnClick(_ sender: Any) {
        
        textView.resignFirstResponder()
        
        textView.inputView = textView.inputView != nil ? nil : emoticonVc.view
        
        textView.becomeFirstResponder()
        
    }

}

//MARK: ---textView代理方法---
extension ComposeViewController:UITextViewDelegate  {
    
    func textViewDidChange(_ textView: UITextView) {
        self.textView.placeHolderLabel.isHidden = textView.hasText
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
    
}

//MARK: ---添加和删除图片---
extension ComposeViewController {
    
    func addPhotoClick() {
        
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            return
        }
        
        let upc = UIImagePickerController()
        
        upc.sourceType = .photoLibrary
        
        upc.delegate = self
        
        present(upc, animated: true, completion: nil)
        
    }
    
    func deletePhotoClick(note:Notification) {
        guard let image = note.object as? UIImage else {
            return
        }
        
        guard let index = images.index(of: image) else {
            return
        }
        
        images.remove(at: index)
        
        picPicker.images = images
    }
    
}

extension ComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        images.append(image)
        
        picPicker.images = images
        
        picker.dismiss(animated: true, completion: nil)
        
    }
    
}
